package com.shuangti.webdemo.filter;

import com.shuangti.webdemo.po.Result;
import com.shuangti.webdemo.util.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 实现servlet提供的filter接口并实现里面的三个方法
 */
@WebFilter(urlPatterns = "/*")//拦截所有请求
@Slf4j
public class MyFilter implements Filter {

//    @Override
//    public void init(FilterConfig filterConfig) throws ServletException {
//        log.info("初始化方法");
//    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("拦截到请求和进行的操作");
        //将servletRequest和servletResponse强转为HttpServletRequest和HttpServletResponse
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        //1.获取请求路径
        String requestURI = request.getRequestURI();
        //2.判断是否是/login请求，如果是放行，如果不是拦截，进行token判断验证
        if (requestURI.contains("/login")){
            log.info("是登录方法，放行");
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //3.获取请求头中的token看是否存在，不存在就是没登录返回错误信息401，存在，验证
        String token = request.getHeader("token");
        if (token == null && token.isEmpty()){
            //返回错误信息
            response.setStatus(401);
            return;
        }

        //4.进行token验证，成功放行，失败，返回错误信息401
        try {
            JwtUtils.parseJWT(token);
        }catch (Exception e){
            log.info("令牌非法");
            response.setStatus(401);
            return;
        }
        //放行
        log.info("令牌合法，放行");
        filterChain.doFilter(servletRequest,servletResponse);
    }

//    @Override
//    public void destroy() {
//      log.info("销毁方法");
//    }
}
